package com.virtual.repository.common.model.adapters;

import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.springframework.util.StringUtils;

import com.virtual.repository.common.model.Property;

/**
 * Class defines methods for adapting a an array of <code>Property</code> elements, represented by <code>Properties</code> class
 * to a map of <code>properties</code> elements, represented by <code>Map<String, Property></code>. 
 * The methods are invoked by the JAXB binding framework during marshaling and unmarshalling.
 * 
 * @author kchaber
 *
 */
public class PropertyMapAdapter extends XmlAdapter<Properties , Map<String, Property>> {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Map<String, Property> unmarshal(Properties properties) throws Exception {
		Map<String, Property> result = new HashMap<>();
		for (Property p : properties.values) {
			//put property indexed by the field name, defined in the class
			result.put(p.getName(), p);
			
			//put property indexed by the entity name, defined in the database's entity/table
			if (!StringUtils.isEmpty(p.getSourceName())) {
				result.put(p.getSourceName(), p);
			}
		}
		
		return result;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Properties marshal(Map<String, Property> v) throws Exception {
		throw new UnsupportedOperationException("This method has not be implemented yet");
	}


}
